import { aliOssSecurityToken } from "@/apis/file";
import AliOssSdk from "ali-oss";

export const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};

export const getAuth = async () => {
  try {
    const { data } = await aliOssSecurityToken();
    return {
      region: "oss-cn-hangzhou",
      bucket: data.bucketName,
      accessKeyId: data.accessKeyId,
      accessKeySecret: data.accessKeySecret,
      stsToken: data.securityToken,
    };
  } catch (err) {
    throw err;
  }
};
export const getClientOss = async () => {
  try {
    const clientOss = await getAuth();
    return new AliOssSdk({
      ...clientOss,
    });
  } catch (err) {
    throw err;
  }
};
export const getProgress = progress => {
  return Math.floor(progress * 100);
};

/**
 * 校验文件重复
 * @param name -文件夹/文件
 * @param options
 */
export const isExistObject = (name, options = {}) => {
  return new Promise(async (resolve, reject) => {
    try {
      const client = await getClientOss();
      await client.head(name, options);
      resolve(true);
    } catch (error) {
      resolve(!(error.code === "NoSuchKey"));
    }
  });
};

/**
 * 文件权限
 * @param ObjName
 * @param configObj
 * @return {Promise<*>}
 */
export const setACL = async (ObjName, configObj) => {
  const client = await getClientOss();
  return await client.putACL(ObjName, configObj);
};

/**
 * 文件url
 * @param ObjName
 * @return {Promise<*>}
 */
export const signatureUrl = async ObjName => {
  const client = await getClientOss();
  return await client.signatureUrl(`${ObjName}`);
};
